/*
 * Copyright 2000-2020 ALPHA LAB.Inc All Rights Reserved.
 */
package com.alphalab.framework.context;

import java.util.Date; 
import org.apache.log4j.Logger; 
import net.sf.ezmorph.object.AbstractObjectMorpher;
import java.sql.Timestamp;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import net.sf.ezmorph.MorphException;

/**
 * 日期转换适配器TimestampMorpher.
 * 接收前端参数数组时，将json对象日期属性的long类型转成javabean的date类型.
 * @author allen 
 * @version 1.0.0 2018年3月10日
 */
public class TimestampMorpher extends AbstractObjectMorpher {
	
	/**
	 * LOG.
	 */
	private static final Logger LOG = Logger.getLogger(TimestampMorpher.class);  
	 
	/**
	 * 类型转换处理.
	 * @param value value
	 * @return Object Object
	 */
	@Override
    public Object morph(final Object value) {  
        if (value == null) {  
            return null;  
        }  
        if (Timestamp.class.isAssignableFrom(value.getClass())) {  
            return (Timestamp) value;  
        }  
        if (!supports(value.getClass())) {  
            throw new MorphException(value.getClass() + " 是不支持的类型");  
        }  
        if (value instanceof Long) {  
        	final Long time = (Long) value; 
            return fomatLongToDate(time);
        }
        if (value instanceof String) { 
        	final String strValue = (String) value;  
        	final Long time = new Long(strValue);  
            return fomatLongToDate(time);
        }  
        return null;  
    }  
    
    @Override  
    public Class morphsTo() {  
    	//目标属性类型
        return Date.class;  
    }  
    /**
     * supports.
     * @param clazz clazz
     * @return boolean
     */
    @Override
    public boolean supports(final Class clazz) {  
        //支持的被转换的类型
        return (Long.class.isAssignableFrom(clazz) | String.class.isAssignableFrom(clazz));  
    }  

    /**
     * 将Long类型转成date类型.
     * @param value value
     * @return Date
     */
    private Date fomatLongToDate(final Long value) {
        final SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        final String dstr = format.format(value);  
        Date date = new Date();
		try {
			date = format.parse(dstr);
		} catch (ParseException e) { 
			LOG.error("json2java日期转换出错");
		}  
		return date;
    }
    
}
